package bairui.international.weixin.portal.miniapp.util;

import java.util.List;
import java.util.stream.Collectors;

import com.lianjing.sh.data.jpa.query.select.Selector;
import com.querydsl.core.BooleanBuilder;

import bairui.international.model.domain.jpa.QTB_City;
import bairui.international.model.domain.jpa.QTB_Province;
import bairui.international.model.domain.jpa.QTB_Town;
import bairui.international.model.domain.jpa.TB_City;
import bairui.international.model.domain.jpa.TB_Province;
import bairui.international.model.domain.jpa.TB_Town;
import bairui.international.service.Service_City;
import bairui.international.service.Service_Province;
import bairui.international.service.Service_Town;

public class DataDeal {

	/**
	 * 收集数据
	 */
	static List<TB_Province> gainData(Service_Province service_Province, Service_City service_City, Service_Town service_Town){
		return service_Province
    		.select(selectProvince(), it->new BooleanBuilder())
    		.list()
    		.stream()
    		.map(it_p->{
    			// 处理cities
    			List<TB_City> cities = service_City
    				.select(selectCity(), it->it.province.eq(it_p))
    				.list()
    				.stream()
    				.map(it_c->{
    					// 处理towns
    					List<TB_Town> towns = service_Town.select(selectTown(), it->it.city.eq(it_c)).list();
    						it_c.addTowns(towns.toArray(new TB_Town[]{}));
    					return it_c;
    				})
    				.collect(Collectors.toList());
    			it_p.addCities(cities.toArray(new TB_City[]{}));
    			return it_p;
    		})
    		.collect(Collectors.toList());
	}
	
	private static Selector<TB_Province, QTB_Province> selectProvince(){
		return new Selector<TB_Province, QTB_Province>() {
			@Override public TB_Province select(Selector<TB_Province, QTB_Province>.PathInfo pathinfo, QTB_Province QRoot) {
				TB_Province bean = new TB_Province();
					pathinfo.select(QRoot.id, it->bean.setId(it));
					pathinfo.select(QRoot.name, it->bean.setName(it));
					pathinfo.select(QRoot.orderValue, it->bean.setOrderValue(it));
				return bean;
			}
		};
	}
	
	private static Selector<TB_City, QTB_City> selectCity(){
		return new Selector<TB_City, QTB_City>() {
			@Override public TB_City select(Selector<TB_City, QTB_City>.PathInfo pathinfo, QTB_City QRoot) {
				TB_City bean = new TB_City();
					pathinfo.select(QRoot.id, it->bean.setId(it));
					pathinfo.select(QRoot.name, it->bean.setName(it));
					pathinfo.select(QRoot.orderValue, it->bean.setOrderValue(it));
				return bean;
			}
		};
	}
	
	private static Selector<TB_Town, QTB_Town> selectTown(){
		return new Selector<TB_Town, QTB_Town>() {
			@Override public TB_Town select(Selector<TB_Town, QTB_Town>.PathInfo pathinfo, QTB_Town QRoot) {
				TB_Town bean = new TB_Town();
					pathinfo.select(QRoot.id, it->bean.setId(it));
					pathinfo.select(QRoot.name, it->bean.setName(it));
					pathinfo.select(QRoot.orderValue, it->bean.setOrderValue(it));
				return bean;
			}
		};
	}
	
}
